package com.example.bbook.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bbook.entity.SpeciesEntity;
import com.example.bbook.entity.UserEntity;
import com.example.bbook.mapper.SpeciesMapper;
import com.example.bbook.mapper.UserMapper;
import com.example.bbook.services.UserService;
import com.example.bbook.util.HashMapTool;
import com.example.bbook.util.PageTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SpeciesMapper speciesMapper;

    public UserEntity getUserByToken(String token) {
        QueryWrapper<UserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("auth", token);
        return userMapper.selectOne(userQueryWrapper);
    }

    @Override
    public UserEntity login(UserEntity user) {
        QueryWrapper<UserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        userQueryWrapper.like("password", user.getPassword());
        // 根据用户名和密码获取指定用户
        UserEntity userEntity = userMapper.selectOne(userQueryWrapper);

        // SSO登陆，更新用户token
        if (userEntity != null) {
            String md5Str = DigestUtils.md5DigestAsHex((userEntity.getPassword() + userEntity.getAvatar()).getBytes());
            userEntity.setAuth(md5Str);
            updateById(userEntity);
            userEntity.setPassword("");
            userEntity.setSalt("");
            return userEntity;
        }
        return null;
    }

    @Override
    public UserEntity register(UserEntity user) {
        QueryWrapper<UserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        userQueryWrapper.eq("password", user.getPassword());
        UserEntity userEntity = userMapper.selectOne(userQueryWrapper);
        if (userEntity != null) {
            user.setId(userEntity.getId());
            updateById(user);
            return userMapper.selectOne(userQueryWrapper);
        }
        if (add(user)) {
            return userMapper.selectOne(userQueryWrapper);
        }
        return null;
    }

    @Override
    public UserEntity getUserById(Integer id) {
        UserEntity userEntity = userMapper.selectById(id);
        userEntity.setPassword("");
        userEntity.setSalt("");
        return userEntity;
    }

    @Override
    public HashMap<String, Object> findAll(PageTool pageConfig, UserEntity user) {
        HashMapTool hashMapTool = new HashMapTool();
        Integer page = 1, pageSize = 10;
        if (pageConfig.normal()) {
            page = pageConfig.getPage();
            pageSize = pageConfig.getPageSize();
        }
        IPage<UserEntity> userPage = new Page<>(page, pageSize);
        QueryWrapper<UserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.orderByDesc("id");
        if (user.getUsername() != null) {
            userQueryWrapper.like("username", user.getUsername());
        }

        ArrayList<HashMap<String, Object>> adminTypeArr = new ArrayList<>();
        QueryWrapper<SpeciesEntity> speciesEntityQueryWrapperAdminTypeArr= new QueryWrapper<>();
        speciesEntityQueryWrapperAdminTypeArr.eq("dict_type", "admin");
        speciesMapper.selectList(speciesEntityQueryWrapperAdminTypeArr).forEach(item->{
            adminTypeArr.add(hashMapTool.getListKeyValue(item.getName(), item.getId(), item.getTitle()));
        });


        UserEntity userEntity = new UserEntity();
        userPage = userMapper.selectPage(userPage, userQueryWrapper);

        List<UserEntity> userEntities = userPage.getRecords();
        userEntity.push("admin", adminTypeArr, "用户角色", new int[]{1, 0, 1, 0}, new String[]{"speciesEntity", "title"});

        userEntities.forEach(item -> {
            item.setPassword("");
            item.setAuth("");
            item.setSalt("");
            item.setSpeciesEntity(speciesMapper.selectById(item.getAdmin()));
        });
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("recode", userEntities);
        resMap.put("columns", userEntity.thisColumns());
        resMap.put("total", userMapper.selectCount(userQueryWrapper));
        return resMap;
    }

    @Override
    public Boolean add(UserEntity user) {
        user.setPassword("123456");
        user.setSalt(DigestUtils.md5DigestAsHex(new Date().toString().getBytes()));
        return userMapper.insert(user) > 0;
    }

    @Override
    public Boolean deleteByIds(Integer[] ids) {
        return userMapper.deleteBatchIds(Arrays.asList(ids)) == ids.length;
    }

    @Override
    public Boolean updateById(UserEntity user) {
        return userMapper.updateById(user) == 1;
    }
}
